package com.hengxinguotong.zhihuichengjian.ui.building;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.UserConstructionAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.UserSelectAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.UserSelectedAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Construction;
import com.hengxinguotong.zhihuichengjian.bean.ConstructionListRes;
import com.hengxinguotong.zhihuichengjian.bean.UserListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/1/17
 */

public class EnterpriseUserSelectActivity extends BaseActivity implements View.OnClickListener, UserConstructionAdapter.OnItemClickListener,
        UserSelectAdapter.OnClickListener, UserSelectAdapter.OnSendMessageListener{
    private static final int UPDATE_CONSTRUCTION = 1001;
    private static final int UPDATE_USER = 1002;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.select_user_rv)
    RecyclerView selectUserRv;
    @BindView(R.id.construction_rv)
    RecyclerView constructionRv;
    @BindView(R.id.user_rv)
    RecyclerView userRv;
    @BindView(R.id.et_project)
    HXEditTextView etProject;

    private int type;//1是选择责任人 2是选择告知人
    private int index = 0;
    private List<User> userList, selectUsers;
    private UserSelectAdapter userAdapter;
    private UserSelectedAdapter userSelectedAdapter;
    private List<Construction> constructionList, selectConstructions;
    private UserConstructionAdapter constructionAdapter;
    private Construction selectConstruction;
    private boolean fromNotice = false;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_CONSTRUCTION:
                    List<Construction> constructions = (List<Construction>) msg.obj;
                    processConstructions(constructions);
                    break;
                case UPDATE_USER:
                    List<User> users = (List<User>) msg.obj;
                    processUsers(users);
                    break;
            }
        }
    };

    private void processUsers(List<User> users) {
        for (User user:users){
            user.setConstructionId(selectConstruction.getConstructionId());
            user.setOrgId(selectConstruction.getOrgId());
            user.setConstructionName(selectConstruction.getConstructionName());
            if(user.isInUsers(selectUsers)){
                user.setChecked(true);
            }else {
                user.setChecked(false);
            }
        }
        constructionList.get(index).setUserList(users);
        userList = users;
        userAdapter.setDataList(userList);
    }

    private void processConstructions(List<Construction> constructions) {
        constructionList = constructions;
        selectConstruction = constructions.get(index);
        selectConstruction.setChecked(true);
        constructionAdapter.setDataList(constructionList);

        if(selectConstruction.getUserList() == null || selectConstruction.getUserList().size() <= 0){
            getUserList(selectConstruction.getOrgId());
        }else {
            userList = selectConstruction.getUserList();
            userAdapter.setDataList(userList);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_select);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 1);//1是选择责任人 2是选择告知人
        selectUsers = (List<User>) getIntent().getSerializableExtra("noticedPersons");
        fromNotice = getIntent().getBooleanExtra("fromNotice", false);
        initView();
        getOrgList("加载中…");
    }

    private void initView() {
        switch (type){
            case 1:
                titleTv.setText("选择责任人");
                break;
            case 2:
                titleTv.setText("选择告知人");
                break;
        }

        if(selectUsers == null){
            selectUsers = new ArrayList<>();
        }
        userSelectedAdapter = new UserSelectedAdapter(this, selectUsers);
        selectUserRv.setAdapter(userSelectedAdapter);
        selectUserRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        userList = new ArrayList<>();
        userAdapter = new UserSelectAdapter(this, userList);
        userAdapter.setOnSendMessageListener(this);
        userAdapter.setOnClickListener(this);
        userRv.setAdapter(userAdapter);
        userRv.setLayoutManager(getLayoutManager());

        constructionList = new ArrayList<>();
        constructionAdapter = new UserConstructionAdapter(this, constructionList);
        constructionAdapter.setOnItemClickListener(this);
        constructionRv.setAdapter(constructionAdapter);
        constructionRv.setLayoutManager(getLayoutManager());
    }

    /**
     * 获取组织列表
     * @param alert
     */
    private void getOrgList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type + "");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/org/listOrg/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ConstructionListRes res = gson.fromJson(json, ConstructionListRes.class);
                    if(res.getStatus() == 1){
                        List<Construction> datas = res.getValue();
                        if(datas == null){
                            datas = new ArrayList<Construction>();
                        }
                        Message msg = mHandler.obtainMessage();
                        msg.what = UPDATE_CONSTRUCTION;
                        msg.obj = datas;
                        msg.sendToTarget();
                    }else {
                        showToast(res.getMsg());
                    }
                }else {
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 根据组织id获取人员列表
     * @param orgId
     */
    private void getUserList(String orgId) {
        JSONObject jsonObject = new JSONObject();
        try {
            if(fromNotice){
                jsonObject.put("orgId", orgId );
            }else {
                jsonObject.put("id", orgId );
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url;
        if(fromNotice){
            url = "/notice/listUser/";
        }else {
            url = "/org/listUser/";
        }
        Utils.requestData("加载中…", this, url + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    UserListRes res = gson.fromJson(json, UserListRes.class);
                    if(res.getStatus() == 1){
                        List<User> datas = res.getValue();
                        if(datas == null){
                            datas = new ArrayList<User>();
                        }
                        Message msg = mHandler.obtainMessage();
                        msg.what = UPDATE_USER;
                        msg.obj = datas;
                        msg.sendToTarget();
                    }else {
                        showToast(res.getMsg());
                    }
                }else {
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.submit_tv, R.id.select_all})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.submit_tv:
                if(selectUsers.size() <= 0){
                    showToast("请至少选择一个人员");
                }else {
                    getSelectConstructions();
                    Intent intent = getIntent();
                    intent.putExtra("selectUsers", (Serializable) selectUsers);
                    intent.putExtra("selectConstructions", (Serializable) selectConstructions);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            case R.id.select_all:
                for(User user:userList){
                    if(!user.isChecked()){
                        user.setChecked(true);
                        selectUsers.add(user);
                    }
                }
                userAdapter.setDataList(userList);
                userSelectedAdapter.setDataList(selectUsers);
                break;
        }
    }

    private void getSelectConstructions(){
        selectConstructions = new ArrayList<>();
        for (User user:selectUsers){
            Construction construction = new Construction();
            construction.setConstructionId(user.getConstructionId());
            construction.setConstructionName(user.getConstructionName());
            construction.setOrgId(user.getOrgId());
            if(!construction.isInConstructions(selectConstructions)){
                selectConstructions.add(construction);
            }
        }
    }

    private LinearLayoutManager getLayoutManager(){
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        return manager;
    }

    @Override
    public void OnSendMessage(int position, boolean isChecked) {
        if(isChecked){
            userList.get(position).setStatus(1);
        }else {
            userList.get(position).setStatus(0);
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                userAdapter.setDataList(userList);
            }
        });
    }

    @Override
    public void onClick(Object o) {
        User user = (User) o;
        if(user.isChecked()){
            user.setChecked(false);
            selectUsers.remove(user);
        }else {
            user.setChecked(true);
            selectUsers.add(user);
        }
        userAdapter.setDataList(userList);
        userSelectedAdapter.setDataList(selectUsers);
        if(selectUsers.size() > 3){
            int width = selectUserRv.getWidth();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
            selectUserRv.setLayoutParams(params);
        }else {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            selectUserRv.setLayoutParams(params);
        }
    }

    @Override
    public void onItemClick(View view, Object o, int position) {
        Construction construction = (Construction) o;
        if(construction == null){
            return;
        }
        index = position;
        selectConstruction = constructionList.get(index);
        for (Construction c:constructionList){
            c.setChecked(false);
        }
        selectConstruction.setChecked(true);
        constructionAdapter.setDataList(constructionList);

        if(selectConstruction.getUserList() == null || selectConstruction.getUserList().size() <= 0){
            getUserList(selectConstruction.getOrgId());
        }else {
            userList = selectConstruction.getUserList();
            userAdapter.setDataList(userList);
        }
    }
}
